<template>
  <div class="app-container calendar-list-container">
    <!--条件查询-->
    <div class="filter-container">
      <el-input  style="width: 200px;" class="filter-item" v-model="query.name" :placeholder="'系统名称'">
      </el-input>
      <el-input  style="width: 200px;" class="filter-item" v-model="query.route" :placeholder="'系统路由'">
      </el-input>
      <el-input  style="width: 200px;" class="filter-item" v-model="query.basepath" :placeholder="'基础路径'">
      </el-input>
      <el-select clearable style="width: 110px" class="filter-item" v-model="query.status" :placeholder="'系统状态'">
        <el-option v-for="item in status" :key="item" :label="item == 1 ? '启用':'禁止访问'" :value="item">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="getList">{{$t('table.search')}}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">{{$t('table.add')}}</el-button>
      <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download"  v-loading="downloadLoading" element-loading-text="正在下载中" @click="handleDownload">{{$t('table.export')}}</el-button>
    </div>
    <!--带边框的表格-->
    <el-table
      :data="tableData"
      border
      v-loading="listLoading" element-loading-text="拼命加载中"
      style="width: 100%">
      <!--展开显示详情-->
      <el-table-column
        type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="id">
              <span>{{ props.row.id }}</span>
            </el-form-item>
            <el-form-item label="系统名称">
              <span>{{ props.row.name }}</span>
            </el-form-item>
            <el-form-item label="系统路由">
              <span>{{ props.row.route }}</span>
            </el-form-item>
            <el-form-item label="系统描述">
              <span>{{ props.row.description }}</span>
            </el-form-item>
            <el-form-item label="创建时间">
              <!--时间戳转换-->
              <span>{{props.row.ctime | parseTime('{y}-{m}-{d} {h}:{i}')}}</span>
            </el-form-item>
            <el-form-item label="排序">
              <span>{{ props.row.orders }}</span>
            </el-form-item>
            <el-form-item label="系统状态">
              <span>{{ props.row.status ==1 ? '启用':'禁止访问' }}</span>
            </el-form-item>
            <el-form-item label="基础路径">
              <span>{{ props.row.basepath }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <!--多选支持-->
      <!--<el-table-column-->
        <!--type="selection"-->
       <!--&gt;-->
      <!--</el-table-column>-->
      <!--自定义索引-->
      <el-table-column
        type="index"
        label="序号"
        align="center"
        :index="indexMethod">
      </el-table-column>
      <el-table-column
        prop="name"
        label="系统名称"
        >
      </el-table-column>
      <el-table-column
        prop="route"
        label="系统路由"
        >
      </el-table-column>
      <el-table-column
        prop="basepath"
        label="基础路径"
        >
      </el-table-column>
      <el-table-column
        prop="orders"
        sortable
        label="系统排序">
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态">
        <template slot-scope="scope">
          <el-button type="danger"　size="mini" v-if="scope.row.status == 0" disabled >关闭</el-button>
          <el-button type="success" size="mini" v-else disabled >启用</el-button>
        </template>
      </el-table-column>
      <!--操作按钮-->
      <el-table-column align="center" :label="$t('table.actions')" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--编辑-->
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{$t('table.edit')}}</el-button>
          <!--删除-->
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="danger" @click="handleDelete(scope.row)">{{$t('table.delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页组件-->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current_page"
        :page-sizes="page_sizes"
        :page-size="page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total_size">
      </el-pagination>
    </div>
    <!--添加系统-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="info" :model="info" label-position="right" label-width="80px" style='width: 400px; margin-left:50px;'>
        <!--prop用于进行表单校验-->
        <el-form-item label="系统名称" prop="name">
          <el-input v-model="info.name"></el-input>
        </el-form-item>
        <el-form-item label="系统路由" prop="route">
          <el-input v-model="info.route"></el-input>
        </el-form-item>
        <el-form-item label="系统描述" prop="description">
          <el-input v-model="info.description"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="orders">
          <el-input v-model.number="info.orders"></el-input>
        </el-form-item>
        <el-form-item label="基础路径" prop="basepath">
          <el-input v-model="info.basepath"></el-input>
        </el-form-item>
        <!--系统状态-->
        <el-form-item :label="'系统状态'" prop="status">
          <el-select clearable style="width: 110px" class="filter-item" v-model="info.status" :placeholder="'状态'">
            <el-option v-for="item in status" :key="item" :label="item == 1 ? '启用':'禁止访问'" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import waves from '@/directive/waves' // 水波纹指令
  import { addSystem, getSystemByPage, editSystem, deleteSystem } from '@/api/upms/system'
  import { parseTime } from '@/utils'
  export default {
    directives: {
      waves
    },
    data() {
      return {
        tableData: null, // 系统查询的数据
        current_page: 1,
        page_sizes: [5, 10, 15, 20, 50],
        page_size: 5,
        total_size: undefined,
        listLoading: true,
        status: [ // 描述状态
          0,
          1
        ],
        info: {
          id: undefined, // 用于添加更新系统
          name: undefined,
          route: undefined,
          description: undefined,
          status: 1,
          basepath: undefined,
          orders: undefined
        },
        query: { // 用于查询系统
          name: undefined,
          route: undefined,
          basepath: undefined,
          status: undefined
        },
        temp: { // 更新数据时用于判断属性值是否被更新
        },
        dialogFormVisible: false, // 添加更新系统的会话窗口
        dialogStatus: undefined, // 会话的状态,是创建还是修改
        textMap: {
          update: '编辑',
          create: '添加系统'
        },
        downloadLoading: false,
        rules: {
          name: [
            { required: true, message: '请输入系统名称', trigger: 'blur' },
            { type: 'string', message: '请输入正确的系统名称', trigger: 'blur' }
          ],
          basepath: [
            { required: true, message: '请输入系统路径', trigger: 'blur' },
            { type: 'string', message: '请输入正确的系统路径', trigger: 'blur' }
          ],
          route: [
            { required: true, message: '请输入系统路由', trigger: 'blur' },
            { type: 'string', message: '请输入正确的路由', trigger: 'blur' }
          ],
          description: [
            { required: true, message: '请输入系统描述', trigger: 'blur' },
            { type: 'string', message: '请输入正确的系统描述', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      deepClon(obj) { // 深度克隆对象
        const proto = Object.getPrototypeOf(obj)
        return Object.assign({}, Object.create(proto), obj)
      },
      indexMethod(index) { // 自定义序号
        return this.page_size * (this.current_page - 1) + index + 1
      },
      handleCreate() { // 创建
        for (var item in this.info) {
          this.info[item] = undefined
        }
        if (this.$refs['info']) {
          this.$refs['info'].clearValidate()
        }
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
      },
      handleUpdate(value) { // 更新
        if (this.$refs['info']) {
          this.$refs['info'].clearValidate()
        }
        // 一定要深度克隆对象,不然容易出bug.比如先编辑然后添加
        this.info = this.deepClon(value)
        this.temp = this.deepClon(value)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      },
      handleDelete(system) {
        this.$confirm('此操作将永久删除该系统信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // system.id本身就是个数组
          this.deleteData(system.id).then(response => {
            if (response.data.code === 0) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message({
                type: 'error',
                message: '删除失败!'
              })
            }
          })
        })
      },
      handleDownload() { // 导出当前页数据到excel
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['系统名称', '系统路由', '基础路径', '系统描述', '排序', '状态', '创建时间']
          const filterVal = ['name', 'route', 'basepath', 'description', 'orders', 'status', 'ctime']
          const data = this.formatJson(filterVal, this.tableData)
          excel.export_json_to_excel(tHeader, data, 'upms-system')
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) { // 格式化时间
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'ctime') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      createData() {
        this.$refs['info'].validate((validate) => {
          if (validate) {
            // 创建系统
            addSystem(this.info).then(response => {
              if (response.data.code === 0) {
                this.dialogFormVisible = false
                this.$message({
                  message: '添加系统成功',
                  type: 'success'
                })
                this.getList()
              } else {
                this.$message({
                  message: '添加系统失败',
                  type: 'error'
                })
              }
            })
          } else {
            this.$message({
              message: '请按提示填入正确的表单信息',
              type: 'info'
            })
          }
        })
      },
      updateData() {
        this.$refs['info'].validate((validate) => {
          if (validate) {
            // 更新数据
            editSystem(this.info).then(response => {
              if (response.data.code === 0) {
                this.dialogFormVisible = false
                this.$message({
                  message: '更新系统信息成功',
                  type: 'success'
                })
                this.getList()
              } else {
                this.$message({
                  message: '更新系统信息失败',
                  type: 'error'
                })
              }
            })
          } else {
            this.$message({
              message: '请按提示填入正确的表单信息',
              type: 'info'
            })
          }
        })
      },
      deleteData(ids) {
        // 删除系统
        const id = [ids]
        deleteSystem(id).then(response => {
          if (response.data.code === 0) {
            this.$message({
              message: '删除系统成功',
              type: 'success'
            })
            this.getList()
          } else {
            this.$message({
              message: '删除系统失败',
              type: 'error'
            })
          }
        })
      },
      getList() {
        this.listLoading = true
        // 加载列表
        getSystemByPage(this.query, this.current_page, this.page_size, 'orders_asc').then(response => {
          this.listLoading = false
          if (response.data.code === 0) {
            const data = response.data.data
            this.tableData = data.list
            this.total_size = data.total
          } else {
            this.$message({
              message: '加载信息失败',
              type: 'error'
            })
          }
        })
      },
      handleSizeChange(pageSize) {
        if (pageSize === this.page_size) {
          return
        }
        this.page_size = pageSize
        this.getList()
      },
      handleCurrentChange(pageNum) {
        if (pageNum === this.current_page) {
          return
        }
        this.current_page = pageNum
        this.getList()
      }
    },
    created() {
      this.getList()
    }
  }
</script>

<style scoped>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
